import { and, eq } from "drizzle-orm";
import { users, userSchema } from "@supersavely/db/schema";
import { db } from "@/lib/db";
import NextAuth from "next-auth";
import { compare } from "bcrypt";
import CredentialsProvider from "next-auth/providers/credentials";
import Google from "next-auth/providers/google";
import Facebook from "next-auth/providers/facebook";
import GitHub from "next-auth/providers/github";
import exp from "constants";

export async function getPasswordHashByEmail(credentials: unknown) {
  const { email } = credentials;
  if (!email) {
    return null;
  }
  return (
    await db.select().from(users).where(eq(users.email, credentials.email))
  )[0];
}

export async function getUserByEmailAndPassword(credentials: unknown) {
  const { email, passwordHash } = credentials;
  if (!email || !passwordHash) {
    return null;
  }
  const validateData = userSchema.parse(credentials);
  if (validateData.mode === "signIn") {
    return (
      await db
        .select()
        .from(users)
        .where(
          and(
            eq(users.passwordHash, validateData.passwordHash),
            eq(users.email, validateData.email),
          ),
        )
    )[0];
  }
}

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: {},
        passwordHash: {},
      },
      authorize: async (credentials) => {
        const expectUser: any = await getPasswordHashByEmail(credentials);
        console.log(expectUser);
        const checkRet = await compare(
          credentials.passwordHash,
          expectUser.passwordHash,
        );
        console.log(checkRet);
        if (!checkRet) {
          throw new Error("User not found / Wrong credentials");
        }

        return { ...expectUser, id: expectUser.id.toString() };
      },
    }),
    Google,
    Facebook,
    GitHub,
  ],
  callbacks: {
    jwt({ token, user }) {
      if (user) {
        token.id = user.id;
        // @ts-ignore
        token.name = user.name;
      }
      console.log("token:", token);
      return token;
    },
    session({ session, token }) {
      // @ts-ignore
      session.user.id = token.id;
      // @ts-ignore
      session.user.name = token.name;
      console.log("session:", session);
      return session;
    },
  },
});
